#__Author__  = white
import socketserver,json,os
class MyTCPHandler(socketserver.BaseRequestHandler):
    def ls(self,*args):
        cmd_dic = args[0]
        fileaddr = cmd_dic["fileaddr"]
        ls_results = os.popen("ls %s"%fileaddr).read()
        print(ls_results)
        if ls_results == "":

            self.request.send("当前目录为空".encode())
        else:
            self.request.send(ls_results.encode())
    def put(self,*args):
        cmd_dic = args[0]
        filename = cmd_dic["filename"] #对应client文件名简称
        filesize = cmd_dic["filesize"]
        fileaddr = cmd_dic["fileaddr"]
        print(fileaddr)
        file = fileaddr + '/'+filename
        if os.path.isfile(file):
            f = open(file+".new",'wb')
        else:
            f = open(file,'wb')
        self.request.send(b"200 ok")
        recv_size = 0
        while recv_size < filesize:
            if int(filesize) - int(recv_size) >=1024:
                size = 1024
            else:
                size = int(filesize) - int(recv_size)
            recv_data = self.request.recv(size)
            f.write(recv_data)
            recv_size += len(recv_data)

        else:

            print("file %s put over"%filename)
    def pwd(self,*args):
        send_data = os.popen("pwd").read()
        print(send_data)
        self.request.send(send_data.encode())
    def cd(self,*args):
        cmd_dic = args[0]
        addr = cmd_dic["addr"]
        cd_result = os.path.isdir(addr)
        if cd_result:
            msg = {
                "cd_result":"success",
                "catalog":addr
            }

            self.request.send(json.dumps(msg).encode())
        else:
            msg = {
            "cd_result": "error",

            }
            self.request.send(json.dumps(msg).encode())
    def handle(self):
        while True:
            try:
                self.data = self.request.recv(1024)
                if not self.data: break
                print(self.data)
                cmd_dic = json.loads(self.data.decode())
                action = cmd_dic["action"]
                if hasattr(self,action):
                    func = getattr(self,action)
                    func(cmd_dic)
            except ConnectionResetError as e:
                print(e)
                continue
if __name__ == "__main__":
    HOST,PORT = "localhost",8889
    server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPHandler)
    server.serve_forever()